import CryptoJS from "crypto-js"

const SECRET_KEY = CryptoJS.enc.Utf8.parse("HsaI2l1VDSKVoFRo");
const SECRET_IV = CryptoJS.enc.Utf8.parse("hMqvDFw4z0QGqXY5");

/**
 * 
 * @param data
 * @returns {string}
 */
export function encrypt(data) {
	if (typeof data === "object") {
		try {
			data = JSON.stringify(data);
		} catch (error) {
			console.log("encrypt error:", error);
			return data
		}
	}
	const encrypted = CryptoJS.AES.encrypt(data, SECRET_KEY, {
		iv: SECRET_IV,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	});
	return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}


/**
 * 
 * @param data
 * @returns {string}
 */
export function decrypt(data) {
	try {
		if (typeof data !== 'string') {
			return false
		}
		if (!data) {
			return ''
		}
		const decrypt = CryptoJS.AES.decrypt(data, SECRET_KEY, {
			iv: SECRET_IV,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
		return decryptedStr.toString();
	} catch {
		return data
	}
}